package com.sxkawzp.util;

import com.sxkawzp.anno.DataScope;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * @author suxingkang
 * @version 1.0
 * @since 2025/1/17 15:26
 */
public class DataScopeHolder {


    private static final ThreadLocal<DataScope> QUERY_SCOPE_THREAD_LOCAL = new ThreadLocal<>();
    private static final ThreadLocal<Map<String, Object>> QUERY_SCOPE_PARAM_THREAD_LOCAL = new ThreadLocal<>();


    public static void add(DataScope queryScope) {
        QUERY_SCOPE_THREAD_LOCAL.set(queryScope);
    }


    public static DataScope get() {
        return QUERY_SCOPE_THREAD_LOCAL.get();
    }


    public static void clear() {
        QUERY_SCOPE_THREAD_LOCAL.remove();
    }


    public static void addParam(String paramName, Object paramValue) {
        Map<String, Object> paramMap = QUERY_SCOPE_PARAM_THREAD_LOCAL.get();
        if (Objects.isNull(paramMap)) {
            paramMap = new HashMap<>();
            QUERY_SCOPE_PARAM_THREAD_LOCAL.set(paramMap);
        }
        paramMap.put(paramName, paramValue);
    }


    public static Object getParam(String paramName) {
        return Optional.ofNullable(QUERY_SCOPE_PARAM_THREAD_LOCAL.get()).map(e -> e.get(paramName)).orElse(null);
    }


    public static void removeParam(String paramName) {
        Optional.ofNullable(QUERY_SCOPE_PARAM_THREAD_LOCAL.get()).ifPresent(e -> e.remove(paramName));
    }


    public static void clearParam() {
        QUERY_SCOPE_PARAM_THREAD_LOCAL.remove();
    }


}
